package test;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Random;

import com.db.priceApp.domain.clientDataBasa.ClientProfile;
import com.db.priceApp.network.Client;
import com.db.priceApp.network.protocol.MessageTranciever;
import com.db.priceApp.service.MessageCostructor;

public class ClientRobot implements Runnable {

	private static final int NUMBER_OF_CLIENTS = 100;
	private volatile String username;
	private volatile ClientProfile clientProfile;
	private volatile MessageTranciever mt;

	public static void main(String[] args) {

		//System.out.printf("starting %d robots%n%n", NUMBER_OF_CLIENTS);

		for (int i = 0; i < NUMBER_OF_CLIENTS; i++) {
			(new Thread(new ClientRobot(i))).start();
		}
	}

	ClientRobot(int number) {
		username = String.format("robot_%d", number);
		clientProfile = new ClientProfile();
		mt = new MessageTranciever();
	}

	private void sendLoginMessage(String login, SelectionKey key) {

		byte[] newOrder = MessageCostructor.createLoginReportMessage(login);
		
		clientProfile.setLogin(login);
		try {
			mt.transmit(newOrder, (SocketChannel) key.channel());
		} catch (IOException e) {
			System.out.println("client failure: " + e.getMessage());
			throw new RuntimeException("client error", e);
		}
	}

	@Override
	public void run() {

		try {
			Client client = new Client();
			client.connectToSocket();
			SelectionKey key = client.getKey();
			byte[] newOrder;

			sendLoginMessage(username, key);

			String[] instruments = { "GA", "GB", "GC" };
			Random rand = new Random();

			while (!Thread.interrupted()) {
				String instrName = instruments[rand.nextInt(instruments.length)];
				boolean subscribe = rand.nextFloat() > 0.5f;

				if (subscribe) {
					newOrder = MessageCostructor
							.createSubscribeRequest(instrName);
				} else {
					newOrder = MessageCostructor
							.createUnsubscribeRequest(instrName);
				}

				mt.transmit(newOrder, (SocketChannel) key.channel());

				try {
					Thread.sleep(5000 + rand.nextInt(1000));
				} catch (InterruptedException ignore) {
				}
			}

		} catch (IOException e) {
			System.out.println("failed to connect to the server");
		}

	}
}
